// pages/new/new.js
const app = getApp()
const api = require('../../utils/api.js')
const util = require('../../utils/util.js')
const config = require('../../config/config')
const storage = require('../../utils/cache.js')
import Poster from '../../components/poster/poster/poster';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    current: 3,
    selected: 0,
    array: [],
    isAllScreen: config.isAllScreen,
    imgSrc: false
  },
  onLoad() {
    this.setData({
      imgUrls: app.globalData.gift.pictures,
    })
  },
  // 点击imgItem触发事件
  choiceImg(e) {
    let that = this
    let index = e.currentTarget.dataset.index
    if (index == this.data.imgUrls.length-1) {
      // that.chooseImg()
      if (app.globalData.is_pay) {
        that.chooseImg()
      } else {
        let data = {
          openid: wx.getStorageSync('openid'),
          proid: wx.getStorageSync('proid'),
          type: 0,
          money: 1
        }
        api.POST('weChatPay/createOrder', data).then(res => {
          if (res.error == 0) {
            wx.requestPayment({
              timeStamp: res.data.timeStamp,
              nonceStr: res.data.nonceStr,
              package: res.data.package,
              signType: 'MD5',
              paySign: res.data.paySign,
              success(res) {
                app.globalData.is_pay = true
                that.chooseImg()
              },
              fail(res) {
                console.log('用户取消支付')
              }
            })
          } else {
            util.showFail(res.msg)
          }
        })
      }
    }
  },
  // 选择手机相册图片
  chooseImg() {
    let _this = this
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        const tempFilePaths = res.tempFilePaths[0]
        _this.save(tempFilePaths)
      }
    })
  },
  // 下一步
  next() {
    this.data.current++
    if (this.data.current === this.data.imgUrls.length) {
      this.setData({
        current: 0
      })
    } else {
      this.setData({
        current: this.data.current
      })
    }
  },
  // 上一步
  prev() {
    this.data.current--
    if (this.data.current === -1) {
      this.setData({
        current: this.data.imgUrls.length-1
      })
    } else {
      this.setData({
        current: this.data.current
      })
    }
  },
  getCurrent(e) {
    this.setData({
      current: e.detail.current
    })
  },
  save(e) {
    let arr = this.data.imgUrls
    arr.splice(-1, 1, {
      u: e
    })
    this.setData({
      hasImg: true,
      imgUrls: arr,
      imgSrc: true
    })
  },
  //写祝福语
  getGreetings(e) {
    this.setData({
      greetings: e.detail.value
    })
  },
  // 保存礼包
  saveGift() {
    if (util.isEmpty(this.data.greetings)) {
      util.showFail('请写下小秘密~')
      return
    }
    let that = this
    let idx = this.data.current
    const imgUrl = that.data.imgUrls[idx].u
    if (idx==3 && this.data.imgSrc == false) {
      util.showFail('请上传图片')
      return
    }
    if (idx == 3 && this.data.imgSrc) {
      wx.uploadFile({
        url: 'https://formal.honghuabin.com/v1/upload/uploadImg',
        filePath: imgUrl,
        name: 'file',
        header: { "Content-Type": "application/json" },
        success(res) {
          if (res.statusCode == 200) {
            let datas = JSON.parse(res.data)
            if (datas.error == 0) {
              that.confirm(datas.data.img_src)
            } else {
              console.log(res.msg)
            }
          } else {
            console.log('请求失败')
          }
        }
      })
    } else {
      that.confirm(imgUrl)
    }
  },
  confirm(e) {
    if (this.data.gift) {
      this.setData({
        title: this.data.title,
        showShare: true,
        buttonCss: 'button-up',
      })
    } else {
      this.makeGift(e)
    }
  },
  makeGift(e) {
    let item = {
      cover: e,
      content: this.data.greetings
    }
    let data = {
      openid: '',
      id: null,
      content: {}
    }
    storage.get('openid').then(res => {
      if (res.errMsg === "getStorage:ok") {
        data.openid = res.data
        this.setData({
          openid: res.data
        })
        storage.get('giftId').then(res => {
          if (res.errMsg === "getStorage:ok") {
            data.id = res.data
            this.setData({
              giftId: res.data
            })
            storage.get('one').then(res => {
              if (res.errMsg === "getStorage:ok") {
                data.content.one = res.data
                storage.get('two').then(res => {
                  if (res.errMsg === "getStorage:ok") {
                    data.content.two = res.data
                    storage.get('three').then(res => {
                      if (res.errMsg === "getStorage:ok") {
                        data.content.three = res.data
                        data.content.four = item
                        data.content = JSON.stringify(data.content)
                        api.POST('user/generateGift', data).then(res => {
                          if (res.error == 0) {
                            storage.remove('one')
                            storage.remove('two')
                            storage.remove('three')
                            this.setData({
                              title: res.data.title,
                              gift: true,
                              showShare: true,
                              buttonCss: 'button-up',
                            })
                          } else {
                            util.showFail(res.msg)
                          }
                        })
                      }
                    })
                  }
                })
              }
            })
          }
        })
      }
    })
  },
  onShareAppMessage(res) {
    this.hideShare()
    let shareObj={
      title: '',
      imageUrl: '/img/share.png',
      path: ''
    }
    if (res.from === 'button') {
      shareObj.title = this.data.title,
      shareObj.path = `/pages/preview/preview?giftId=${this.data.giftId}`
    }else {
      if(this.data.gift){
        shareObj.title = this.data.title,
        shareObj.path = `/pages/preview/preview?giftId=${this.data.giftId}`
      }else{
        shareObj.title = '一起来制作2019新年大礼包~',
        shareObj.path = '/pages/home/home'
      }
    }
    return shareObj
  },
  hideShare() {
    this.setData({
      buttonCss: 'button-down',
      showShare: false
    })
  },
  /**
    * 生成分享海报
    * */
  onCreatePoster() {
    let param = {
      openid: this.data.openid,
      id: this.data.giftId,
      path: 'pages/preview/preview',
      scene: this.data.giftId * 1
    }
    api.POST('user/getPoster', param).then(res => {
      this.hideShare()
      this.setData({
        posterConfig: res.data.posterConfig,
      }, () => {
        Poster.create();
      })
    })
  },
  onPosterSuccess(e) {
    const { detail } = e;
    wx.previewImage({
      current: detail,
      urls: [detail]
    })
  },
  onPosterFail(err) {
    console.error(err);
  },
  backHome() {
    wx.reLaunch({
      url: '/pages/home/home'
    })
  }
})